import type {NavigateFunction, NavigateOptions} from 'react-router-dom'
import {To, useNavigate as useRawNavigate} from 'react-router-dom'
import {useIsWorkspace} from './useParams.ts'
import {useAtomCallback} from 'jotai/utils'
import {activeTabKeyAtom, workspaceTabsAtom,} from '../components/WorkspaceTabs'

export function useNavigate(): NavigateFunction {
  const navi = useRawNavigate()
  const isWorkspace = useIsWorkspace()
  return useAtomCallback(
    (get, set, to: To | number, options?: NavigateOptions) => {
      if (isWorkspace) {
        const activeTab = get(activeTabKeyAtom)
        if (!activeTab) return
        if (typeof to === 'number') {
          // TODO: 回退
          return
        }
        const href =
          typeof to === 'string'
            ? to
            : to.pathname + '?' + new URLSearchParams(to.search).toString()
        set(workspaceTabsAtom, (tabs) => {
          return tabs.map((tab) => {
            if (tab.key === activeTab) {
              return {
                ...tab,
                path: href,
              }
            }
            return tab
          })
        })
        return
      }
      if (typeof to === 'number') {
        return navi(to)
      }
      return navi(to, options)
    },
  )
}
